<template>
  <div class="p-4">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-900">银行明细管理</h1>
      <p class="text-gray-600 mt-1">查看和管理银行交易明细</p>
    </div>

    <!-- 统计卡片 -->
    <div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
      <Card
        v-for="card in statisticCards"
        :key="card.title"
        class="w-full shadow-sm"
        :body-style="{ padding: '16px' }"
      >
        <div class="flex flex-col">
          <span class="text-sm text-gray-500">{{ card.title }}</span>
          <span :class="['mt-2 text-2xl font-semibold', card.color]">
            {{ card.value }}
          </span>
        </div>
      </Card>
    </div>

    <!-- 搜索和列表区域 -->
    <Card>
      <!-- 操作区域 -->
      <div class="mb-6">
        <div class="flex flex-wrap gap-4 items-center justify-between">
          <div class="flex flex-wrap gap-4 items-center">
            <!-- 匹配状态筛选 -->
            <div>
              <label class="text-sm text-gray-600 mr-2">匹配状态:</label>
              <Select
                v-model:value="filters.match_status"
                @change="fetchBankDetails"
                style="width: 120px"
                placeholder="全部"
              >
                <Select.Option value="">全部</Select.Option>
                <Select.Option value="未匹配">未匹配</Select.Option>
                <Select.Option value="已匹配">已匹配</Select.Option>
                <Select.Option value="已忽略">已忽略</Select.Option>
              </Select>
            </div>

            <!-- 收支类型筛选 -->
            <div>
              <label class="text-sm text-gray-600 mr-2">收支:</label>
              <Select
                v-model:value="filters.cd_sign"
                @change="fetchBankDetails"
                style="width: 100px"
                placeholder="全部"
              >
                <Select.Option value="">全部</Select.Option>
                <Select.Option value="0">收入</Select.Option>
                <Select.Option value="1">支出</Select.Option>
              </Select>
            </div>

            <!-- 搜索 -->
            <div>
              <Input
                v-model:value="filters.search"
                @press-enter="fetchBankDetails"
                placeholder="搜索流水号、户名..."
                style="width: 200px"
              />
            </div>

            <Button type="primary" @click="fetchBankDetails">
              搜索
            </Button>
          </div>

          <div class="flex gap-2">
            <Button type="primary" ghost :loading="syncing" :disabled="syncing" @click="handleSyncBankDetails">
              获取银行明细(两次点击请间隔10分钟)
            </Button>
            <Button @click="fetchBankDetails">
              刷新
            </Button>
          </div>
        </div>
      </div>

      <!-- 银行明细列表 -->
      <div>
        <div class="mb-4">
          <h3 class="text-lg font-semibold">银行明细列表</h3>
        </div>

        <Spin :spinning="loading">
          <Table
            :columns="columns"
            :data-source="bankDetails"
            :pagination="{
              current: pagination.current_page,
              pageSize: pagination.per_page,
              total: pagination.total,
              showSizeChanger: false,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'serial_no'">
                <span class="text-blue-600 font-medium">{{ record.serial_no }}</span>
              </template>
              <template v-if="column.key === 'transaction_datetime'">
                {{ formatDate(record.transaction_datetime) }}
              </template>
              <template v-if="column.key === 'amt'">
                <span class="font-medium" :class="record.cd_sign === '0' ? 'text-green-600' : 'text-red-600'">
                  {{ record.cd_sign === '0' ? '+' : '-' }}¥{{ record.amt }}
                </span>
              </template>
              <template v-if="column.key === 'cd_sign'">
                <Tag :color="record.cd_sign === '0' ? 'green' : 'red'">
                  {{ record.cd_sign === '0' ? '收入' : '支出' }}
                </Tag>
              </template>
              <template v-if="column.key === 'opp_acc_name'">
                {{ record.opp_acc_name || '-' }}
              </template>
              <template v-if="column.key === 'match_status'">
                <Tag :color="getMatchStatusColor(record.match_status)">
                  {{ record.match_status || '未知状态' }}
                </Tag>
              </template>
              <template v-if="column.key === 'action'">
                <Space>
                  <Button type="link" size="small" @click="viewDetail(record)">
                    查看详情
                  </Button>
                  <Button
                    v-if="record.match_status === '未匹配'"
                    type="link"
                    size="small"
                    @click="markAsIgnored(record.id)"
                  >
                    忽略
                  </Button>
                </Space>
              </template>
            </template>
          </Table>
        </Spin>
      </div>
    </Card>

    <!-- 详情模态框 -->
    <div v-if="showDetail" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-lg max-w-3xl w-full m-4 max-h-96 overflow-y-auto">
        <div class="p-4 border-b flex justify-between items-center">
          <h3 class="text-lg font-semibold">银行明细详情</h3>
          <button @click="showDetail = false" class="text-gray-500 hover:text-gray-700">
            <span class="text-xl">&times;</span>
          </button>
        </div>
        <div class="p-4" v-if="selectedDetail">
          <div class="grid grid-cols-2 gap-4 text-sm mb-4">
            <div>
              <span class="text-gray-600">流水号:</span>
              <span class="ml-2 font-medium">{{ selectedDetail.serial_no }}</span>
            </div>
            <div>
              <span class="text-gray-600">交易时间:</span>
              <span class="ml-2">{{ formatDate(selectedDetail.transaction_datetime) }}</span>
            </div>
            <div>
              <span class="text-gray-600">金额:</span>
              <span class="ml-2 font-medium" :class="selectedDetail.cd_sign === '0' ? 'text-green-600' : 'text-red-600'">
                {{ selectedDetail.cd_sign === '0' ? '+' : '-' }}¥{{ selectedDetail.amt }}
              </span>
            </div>
            <div>
              <span class="text-gray-600">余额:</span>
              <span class="ml-2">¥{{ selectedDetail.bal }}</span>
            </div>
            <div>
              <span class="text-gray-600">对方户名:</span>
              <span class="ml-2">{{ selectedDetail.opp_acc_name || '未知' }}</span>
            </div>
            <div>
              <span class="text-gray-600">对方账号:</span>
              <span class="ml-2">{{ selectedDetail.opp_acc_no || '未知' }}</span>
            </div>
            <div>
              <span class="text-gray-600">对方银行:</span>
              <span class="ml-2">{{ selectedDetail.opp_acc_bank || '未知' }}</span>
            </div>
            <div>
              <span class="text-gray-600">匹配状态:</span>
              <span class="ml-2" :class="getMatchStatusClass(selectedDetail.match_status)">
                {{ selectedDetail.match_status || '未知状态' }}
              </span>
            </div>
            <div class="col-span-2">
              <span class="text-gray-600">摘要:</span>
              <span class="ml-2">{{ selectedDetail.abs || '无' }}</span>
            </div>
          </div>

          <!-- 匹配建议 -->
          <div v-if="matchSuggestions.length > 0" class="border-t pt-4">
            <h4 class="font-medium mb-2">匹配建议:</h4>
            <div class="space-y-2">
              <div v-for="suggestion in matchSuggestions" :key="suggestion.recharge.id"
                   class="border rounded p-3 hover:bg-gray-50">
                <div class="flex justify-between items-start">
                  <div class="text-sm">
                    <div class="font-medium">{{ suggestion.recharge.recharge_number }}</div>
                    <div>金额: ¥{{ suggestion.recharge.amount }}</div>
                    <div>落地公司: {{ suggestion.recharge.landing_company }}</div>
                    <div>置信度: {{ Math.round(suggestion.confidence * 100) }}%</div>
                    <div class="text-xs text-gray-500 mt-1">
                      匹配原因: {{ suggestion.match_reasons.join(', ') }}
                    </div>
                  </div>
                  <button
                    @click="confirmMatchSuggestion(suggestion.recharge.id, selectedDetail.id)"
                    class="bg-green-500 text-white px-3 py-1 rounded text-xs hover:bg-green-600"
                  >
                    确认匹配
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 如果已匹配，显示匹配的充值信息 -->
          <div v-if="selectedDetail.match_status === '已匹配' && selectedDetail.recharge" class="border-t pt-4">
            <h4 class="font-medium mb-2">匹配的充值申请:</h4>
            <div class="bg-green-50 p-3 rounded">
              <div class="text-sm">
                <div class="font-medium">{{ selectedDetail.recharge.recharge_number }}</div>
                <div>金额: ¥{{ selectedDetail.recharge.amount }}</div>
                <div>落地公司: {{ selectedDetail.recharge.landing_company }}</div>
                <div>置信度: {{ Math.round(selectedDetail.match_confidence * 100) }}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import {
  getBankDetailListApi,
  getBankDetailApi,
  updateBankDetailStatusApi,
  confirmMatchApi,
  syncBankDetailsApi,
  type FinanceApi
} from '#/api/core/finance'
import { Button, Card, Input, Select, Table, Tag, Spin, Space, message } from 'ant-design-vue'

// 数据定义
const loading = ref(false)
const showDetail = ref(false)
const selectedDetail = ref<FinanceApi.BankDetailRecord | null>(null)
const matchSuggestions = ref<FinanceApi.MatchSuggestion[]>([])

const syncing = ref(false)
const lastSyncTimestamp = ref<number | null>(null)
const SYNC_INTERVAL = 10 * 60 * 1000

const bankDetails = ref<FinanceApi.BankDetailRecord[]>([])
const pagination = reactive({
  current_page: 1,
  per_page: 20,
  total: 0,
  last_page: 1
})

const statistics = reactive({
  totalDetails: 0,
  unmatchedCount: 0,
  matchedCount: 0,
  totalAmount: 0
})

const formatNumber = (value: number) => new Intl.NumberFormat('zh-CN').format(value || 0)
const formatCurrency = (value: number) => new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(value || 0)

const statisticCards = computed(() => [
  {
    title: '总明细数',
    value: formatNumber(statistics.totalDetails),
    color: 'text-blue-600'
  },
  {
    title: '未匹配',
    value: formatNumber(statistics.unmatchedCount),
    color: 'text-orange-500'
  },
  {
    title: '已匹配',
    value: formatNumber(statistics.matchedCount),
    color: 'text-green-600'
  },
  {
    title: '收入总额',
    value: formatCurrency(statistics.totalAmount),
    color: 'text-purple-600'
  },
])

const filters = reactive({
  match_status: '' as FinanceApi.BankDetailListParams['match_status'] | '',
  cd_sign: '' as FinanceApi.BankDetailListParams['cd_sign'] | '',
  search: '',
  page: 1
})

// 表格列配置
const columns = [
  {
    title: '流水号',
    dataIndex: 'serial_no',
    key: 'serial_no',
  },
  {
    title: '交易时间',
    dataIndex: 'transaction_datetime',
    key: 'transaction_datetime',
  },
  {
    title: '金额',
    dataIndex: 'amt',
    key: 'amt',
  },
  {
    title: '收支',
    dataIndex: 'cd_sign',
    key: 'cd_sign',
  },
  {
    title: '对方户名',
    dataIndex: 'opp_acc_name',
    key: 'opp_acc_name',
  },
  {
    title: '匹配状态',
    dataIndex: 'match_status',
    key: 'match_status',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 辅助函数
const getMatchStatusColor = (status: string) => {
  const colorMap = {
    '未匹配': 'orange',
    '已匹配': 'green',
    '已忽略': 'default'
  }
  return colorMap[status] || 'default'
}

const getMatchStatusClass = (status: string) => {
  const classMap = {
    '未匹配': 'bg-orange-100 text-orange-800',
    '已匹配': 'bg-green-100 text-green-800',
    '已忽略': 'bg-gray-100 text-gray-800'
  }
  return classMap[status] || 'bg-gray-100 text-gray-800'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// API 调用函数
const fetchBankDetails = async () => {
  loading.value = true
  try {
    const params: FinanceApi.BankDetailListParams = {
      page: filters.page,
      per_page: pagination.per_page
    }

    if (filters.match_status) params.match_status = filters.match_status
    if (filters.cd_sign) params.cd_sign = filters.cd_sign
    if (filters.search) params.search = filters.search

    const response = await getBankDetailListApi(params)

    bankDetails.value = response.list
    Object.assign(pagination, response.pagination)

    // 更新统计信息
    const stats = response.statistics
    statistics.totalDetails = pagination.total
    statistics.unmatchedCount = stats?.match_status_counts?.['未匹配'] || 0
    statistics.matchedCount = stats?.match_status_counts?.['已匹配'] || 0
    statistics.totalAmount = stats?.total_amount || 0
  } catch (error) {
    console.error('请求失败:', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}
const handleSyncBankDetails = async () => {
  if (syncing.value) return;
  const now = Date.now();
  if (lastSyncTimestamp.value && now - lastSyncTimestamp.value < SYNC_INTERVAL) {
    const remainingMs = SYNC_INTERVAL - (now - lastSyncTimestamp.value);
    const remainingMinutes = Math.ceil(remainingMs / 60000);
    message.warning(`请至少间隔10分钟再获取，约 ${remainingMinutes} 分钟后重试`);
    return;
  }
  syncing.value = true;
  try {
    await syncBankDetailsApi();
    lastSyncTimestamp.value = now;
    message.success('已提交获取银行明细任务，请稍后刷新');
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '触发银行明细同步失败';
    message.error(errorMessage);
  } finally {
    syncing.value = false;
  }
};


const viewDetail = async (detail: FinanceApi.BankDetailRecord) => {
  try {
    const response = await getBankDetailApi(detail.id)
    selectedDetail.value = response.detail
    matchSuggestions.value = response.match_suggestions || []
    showDetail.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    message.error('获取详情失败')
  }
}

const markAsIgnored = async (detailId: string) => {
  if (!confirm('确认要忽略这条明细吗？')) return

  try {
    await updateBankDetailStatusApi(detailId, '已忽略', '手动忽略')
    message.success('操作成功')
    fetchBankDetails()
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败')
  }
}

const confirmMatchSuggestion = async (rechargeId: string, bankDetailId: string) => {
  if (!confirm('确认要建立这个匹配关系吗？')) return

  try {
    await confirmMatchApi(rechargeId, bankDetailId)
    message.success('匹配确认成功')
    showDetail.value = false
    fetchBankDetails()
  } catch (error) {
    console.error('确认失败:', error)
    message.error('确认失败')
  }
}

const changePage = (page: number) => {
  if (page < 1 || page > pagination.last_page) return
  filters.page = page
  fetchBankDetails()
}

// 表格分页变化处理
const handleTableChange = (paginationInfo: any) => {
  filters.page = paginationInfo.current
  fetchBankDetails()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchBankDetails()
})
</script>

<style scoped>
/* 如果需要额外的样式可以在这里添加 */
</style>
